package com.esm.sm800.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.esm.sm800.R;
import com.esm.sm800.database.dbmodel.Draw_report;
import com.esm.sm800.database.dbmodel.Needle;
import com.esm.sm800.database.dbmodel.SystemAllInfo;
import com.esm.sm800.database.manager.DrawreportCenter;
import com.esm.sm800.database.manager.SystemCenter;
import com.esm.sm800.util.Camera2Manager;
import com.esm.sm800.util.JtComm;
import com.esm.sm800.util.Utils;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import zuo.biao.library.base.BaseActivity;

//还针检测
public class HzjcActivity extends BaseActivity implements View.OnClickListener {

    private final String TAG = "HzjcActivity";

    private ImageView iv_pic;
    TextView tv_sbjg;
    TextView tv_needle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_hzjc);

        iv_pic = (ImageView) findViewById(R.id.iv_pic);
        tv_sbjg = (TextView) findViewById(R.id.tv_sbjg);
        tv_needle = (TextView) findViewById(R.id.tv_needle);

        findViewById(R.id.tv_dksxt).setOnClickListener(this);
        findViewById(R.id.tv_duanzhen).setOnClickListener(this);
        findViewById(R.id.tv_hege).setOnClickListener(this);

        tv_sbjg.setText("");
        _needleHz = SystemCenter.getInstance().needleHz;
        if (_needleHz == null) {
            showShortToast(getString(R.string.wxzzw));
            finish();
            return;
        }

        if (SystemCenter.getInstance().drEdit == null) {
            showShortToast(getString(R.string.wxjzjl));
            finish();
            return;
        }

        tv_needle.setText(_needleHz.getName() + getString(R.string.cduwp) + _needleHz.getLength() + " ]");

        setDuanzhenset();//设置断针的范围区间[_minLen, _maxLen]

    }

    int _minLen = 0;
    int _maxLen = 10000;

    private void setDuanzhenset() {
        int len = _needleHz.getLength();
        _minLen = (int) (len * 0.8);
        _maxLen = (int) (len * 1.2);

        try {
            SystemAllInfo dzzd = SystemCenter.getInstance().getSysInfo("dzzd");
            if (dzzd != null) {
                _minLen = (int) (Integer.parseInt(dzzd.getContent()) * len / 100.0);
            }
            SystemAllInfo dzzc = SystemCenter.getInstance().getSysInfo("dzzc");
            if (dzzc != null) {
                _maxLen = (int) (Integer.parseInt(dzzc.getContent()) * len / 100.0);
            }
        } catch (Exception e) {
            Toast.makeText(HzjcActivity.this, "错误的数字！", Toast.LENGTH_SHORT).show();
        }
    }

    Needle _needleHz = null;

    public static final int FINISH_SB = 1101;
    public static final int DOPAIZHAO = 1103;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == FINISH_SB) {
                dismissProgressDialog();
                if (_len >= 0) {
                    tv_sbjg.setText(getString(R.string.changduwei) + " "+ _len);
                    showShortToast(getString(R.string.changduwei) + _len);
                } else {
                    tv_sbjg.setText(getString(R.string.changduwei));
                    showShortToast(getString(R.string.yichangchucuo));
                }
            } else if (msg.what == DOPAIZHAO) {
                Camera2Manager.get().rePz();//不能在线程里调用
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.tv_dksxt:
                onShibie();
                break;
            case R.id.tv_duanzhen:
                onDuanzhen();
                break;
            case R.id.tv_hege:
                onHege();
                break;
        }
    }

    private void onDuanzhen() {
        if (Utils.isFastDoubleClick()) {
            return;
        }
        int needlelen = _needleHz.getLength();

        if (needlelen < _minLen || needlelen > _maxLen) {
            showShortToast(getString(R.string.cdbfhbnzwdzh));
            return;
        }

        showShortToast(getString(R.string.cdfjkhdz));

        SystemCenter.getInstance().memberTgr = null;
        SystemCenter.getInstance().logintype = 4;//断针通过人登录
        Intent intent = new Intent(this, LoginActivity.class);
        startActivityForResult(intent, 103);

    }

    private void doDuanzhen() {
        //获取当前日期
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date();
        String strDate = formatter.format(curDate);
        //

        //还针记录
        Draw_report dr = SystemCenter.getInstance().drEdit;
        dr.setUpdate_time(strDate);
        dr.setType(2);
        dr.setReturn_time(strDate);
        dr.setImg(_currentPhotoPath);

        SystemCenter.getInstance().drEdit = dr;

        //增加海绵的已用针数
        addyyzs();

        JtComm.getInstance().sendCommand_hsz();//回收针

        Intent intent = new Intent(this, DzinfoActivity.class);
        startActivityForResult(intent, 600);
    }

    private void onHege() {
        int needlelen = _needleHz.getLength();
        if (Math.abs(needlelen - _len) > 5) {
            showShortToast(getString(R.string.cdbfhbnzwzczh));
            return;
        }

        showShortToast(getString(R.string.cdfhzchz));
        //正常还针
        //获取当前日期
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date();
        String strDate = formatter.format(curDate);
        //

        //还针记录
        Draw_report dr = SystemCenter.getInstance().drEdit;
        dr.setUpdate_time(strDate);
        dr.setType(1);
        dr.setReturn_time(strDate);
        dr.setImg(_currentPhotoPath);
        DrawreportCenter.getInstance().saveDraw_report(dr);

        //增加海绵的已用针数
        addyyzs();

        //不增加库存--需要打开补仓针么？还是仓储仓？ -- 进回收仓
        setResult(RESULT_OK);
        finish();
    }

    //增加海绵的已用针数
    void addyyzs() {
        SystemAllInfo yyzs = SystemCenter.getInstance().getSysInfo("yyzs");
        int yyzNum = 0;//已用针
        try {
            yyzNum = Integer.parseInt(yyzs.getContent());
        } catch (Exception e) {
            showShortToast(getString(R.string.cwdsz));
            return;
        }
        yyzNum += 1;
        SystemCenter.getInstance().saveSysInfo(new SystemAllInfo(null, "yyzs", yyzNum + ""));
    }

    private static final int REQUEST_IMAGE_CAPTURE = 2;
    private Uri mImageUri;

    int _len = 0;//识别的长度-像素
    boolean _isshibieing = false;

    private void onShibie() {
        if (_isshibieing) {
            return;
        }
        tv_sbjg.setText("");
        _isshibieing = true;
        showProgressDialog(getString(R.string.zzsbiezhong));

        new Thread() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(DOPAIZHAO);
                while (true) {
                    int t = 0;
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    t++;
                    _len = Camera2Manager.get().getNeedelen();
                    if (_len >= 0 || t > 5) {
                        break;
                    }
                }

                _isshibieing = false;
                mHandler.sendEmptyMessage(FINISH_SB);
            }
        }.start();

    }

    @Override
    protected void onResume() {
        super.onResume();
        Camera2Manager.get()._imageView = iv_pic;
    }

    @Override
    protected void onPause() {
        super.onPause();
        Camera2Manager.get()._imageView = null;

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    String _currentPhotoPath = "";//图片保存的途径

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_IMAGE_CAPTURE) {
            if (data != null) {
                //将返回的图片数据使用Bitmap类型变量targetBitmap 接收
                Bitmap orgPic = data.getParcelableExtra("data");
                int w = orgPic.getWidth();//250
                int h = orgPic.getHeight();//187

                if (SystemCenter.getInstance().hzBitmap != null && !SystemCenter.getInstance().hzBitmap.isRecycled()) {
                    SystemCenter.getInstance().hzBitmap.recycle();
                    SystemCenter.getInstance().hzBitmap = null;
                }

                SystemCenter.getInstance().hzBitmap = orgPic;
//                saveBitmapToFile(SystemCenter.getInstance().hzBitmap);
            }
        }

        if (resultCode != RESULT_OK) {
            return;
        }

        if (requestCode == 111) {
            //已不使用
            Uri imageUri = data.getData();//得到图片的路径
            InputStream imageStream;//得到基于路径的流文件
            try {
                imageStream = getContentResolver().openInputStream(imageUri);
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
            Bitmap selectImage = BitmapFactory.decodeStream(imageStream);//得到了图片的位图
            if (selectImage != null && !selectImage.isRecycled()) {
                if (SystemCenter.getInstance().hzBitmap != null && !SystemCenter.getInstance().hzBitmap.isRecycled()) {
                    SystemCenter.getInstance().hzBitmap.recycle();
                    SystemCenter.getInstance().hzBitmap = null;
                }
//                SystemCenter.getInstance().hzBitmap = convertToGrayscale(selectImage);
                iv_pic.setImageBitmap(SystemCenter.getInstance().hzBitmap);

                selectImage.recycle();
            }
        } else if (requestCode == 600) {
            //编辑断针信息
            setResult(RESULT_OK);
            finish();
        } else if (requestCode == 103) {
            doDuanzhen();
        }
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {

    }

}
